package icu.groot.alan.hotel.controller.comment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import icu.groot.alan.hotel.entity.dao.CommentDo;
import icu.groot.alan.hotel.entity.dao.RoomDo;
import icu.groot.alan.hotel.service.CommentService;
import icu.groot.alan.hotel.service.RoomService;
import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.GrootApi;
import icu.groot.alan.hotel.util.LoginTokenEntity;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import icu.groot.alan.hotel.util.response.Result;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * comment management
 */
@RequestMapping("/comment")
@RestController

public class CommentController {

    @Resource
    CommentService commentService;
    @Resource
    RoomService roomService;

    @PostMapping("/list/{roomCode}")
    public Result<List<CommentDo>> listByRoomCode(@PathVariable("roomCode") String roomType){
        if (roomType == null || roomType.equals("")){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("参数不全"));
        }
        QueryWrapper<CommentDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_type", roomType);
        List<CommentDo> list = commentService.list(queryWrapper);
        return Result.success(list);
    }

    @PostMapping("/add/{roomType}/{comment}")
    public Result<CommentDo> addComment(@PathVariable("roomType") String roomType, @PathVariable("comment") String comment, HttpServletRequest request){
        if (comment == null || comment.equals("") || comment.length() > 24 || roomType == null || roomType.equals("")){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("参数不符合要求"));
        }

        RoomDo roomServiceOne = roomService.getOne(new QueryWrapper<RoomDo>().eq("room_type", roomType));
        if (roomServiceOne == null){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("未找到该房间"));
        }
        CommentDo commentDo = new CommentDo();
        commentDo.setComment(comment);
        commentDo.setRoomType(roomServiceOne.getRoomType());
        commentDo.setCreatedTime(LocalDateTime.now());
        commentDo.setAccName(new Gson().fromJson(request.getAttribute(GrootApi.Jwt.HEADER).toString(), LoginTokenEntity.class).getAccName());
        if (!commentService.save(commentDo)) {
            throw new BizException(ResultCodeEnum.SYSTEM_EXCEPTION);
        }
        return Result.success("评论成功", commentDo);
    }
}
